package com.woniuxy.controller.commonController;

import com.woniuxy.demo.Result;

import com.woniuxy.dto.UserRelatedDto.UserTableDetails;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.ActiveCodeException;
import com.woniuxy.util.CommonsUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/pawn-activeCode")
@Api(tags = "公用接口/发验证码")
public class PawnActiveCodeController {
    @Resource
    private StringRedisTemplate srt;

    /**
     * 验证码
     *
     * @return
     */
    @PostMapping("captcha.do/{phone}")
    @ApiImplicitParam(name = "phone", value = "电话号码")
    public Result captcha(@PathVariable String phone) {
        //获取6位随机验证码
        String randomString = new CommonsUtil().getRandomString(6);
        //获取登录信息
        UserTableDetails ws = ((UserTableDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal());

        if (!ws.getUserPhone().equals(phone)) throw new ActiveCodeException(CodeEnum.CODE_ERROR_PHONE.getMessage(), CodeEnum.CODE_ERROR_PHONE.getCode());


        srt.opsForValue().set("pawn:activeCode:phone:" + phone, randomString);
        //设置过期时间
        srt.expire("pawn:activeCode:phone:" + phone, 2, TimeUnit.HOURS);


        System.out.println("验证码!!!!!!!!!!!!!!" + randomString);

        return Result.newInstance().setCode(200).setMsg("验证码发送成功");
    }
}
